package socket编程计算器;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Server extends Application {
    @Override   // Override the start method in the Application class  覆盖 Application 类中的 start 方法
    public void start(Stage primaryStage) {
        // Text area for displaying contents  显示内容的文本区域
        TextArea ta = new TextArea();

        // Create a scene and place it in the stage  创建一个场景并将其放置在舞台上
        Scene scene = new Scene(new ScrollPane(ta), 450, 200);
        primaryStage.setTitle("Server");  // Set the sage title  设置标题
        primaryStage.setScene(scene);  // Place the scene in the stage  将场景放置在舞台上
        primaryStage.show();  // Display the stage  展示舞台

        new Thread(() -> {
            try {
                // Create a server socket
                // 创建服务器套接字
                ServerSocket serverSocket = new ServerSocket(8000);
                Platform.runLater(() ->
                        ta.appendText("Server started at " + new Date() + '\n'));

                // Listen for a connection request
                // 监听连接请求
                Socket socket = serverSocket.accept();

                // Create data input and output streams
                // 创建数据输入和输出流
                DataInputStream inputFromClient = new DataInputStream(
                        socket.getInputStream());
                DataOutputStream outputToClient = new DataOutputStream(
                        socket.getOutputStream());

                while (true) {
                    // Receive radius from the client
                    // 从客户端接收半径
                    double radius = inputFromClient.readDouble();
                    // Compute area
                    // 计算区域
                    double area = radius * radius * Math.PI;
                    // Send area back to the client
                    // 将区域发送回客户端
                    outputToClient.writeDouble(area);

                    Platform.runLater(() -> {
                        ta.appendText("Radius received from client: " + radius + '\n');
                        ta.appendText("Area is: " + area + '\n');
                    });
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }).start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
